package com.cn.qtms.dao;//类注释设置模板

import com.cn.qtms.base.dao.BaseDao;
import com.cn.qtms.entity.TmSysResource;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * @Name:TmSysResourceDao
 * @Description:
 * @Author: zhangyang
 * @Date 2019-11-13 21:14
 **/
@Repository
public interface TmSysResourceDao extends BaseDao<TmSysResource, Long> {
    /**
     * 获取用户对象的菜单集合
     * @param roles
     * @return
     */
    @Query(value = "SELECT DISTINCT res.* FROM ( " +
            "SELECT * FROM tm_sys_resource WHERE id IN (SELECT parent_id " +
            "FROM tm_sys_resource WHERE id IN (SELECT DISTINCT resource.parent_id " +
            "FROM tm_sys_resource resource,tr_role_resource roleRes,tm_sys_role role " +
            "WHERE roleRes.resource_id = resource.id AND roleRes.role_id = role.id " +
            "AND role.role_code IN ( :roles ) AND resource.res_type IN ( 'api', 'url' ) ) ) " +
            "UNION ALL " +
            "SELECT * FROM tm_sys_resource WHERE id IN ( " +
            "SELECT DISTINCT resource.parent_id FROM tm_sys_resource resource,tr_role_resource roleRes,tm_sys_role role " +
            "WHERE roleRes.resource_id = resource.id AND roleRes.role_id = role.id " +
            "AND role.role_code IN ( :roles ) AND resource.res_type IN ( 'api', 'url' ) ) " +
            "UNION ALL " +
            "SELECT DISTINCT resource.* " +
            "FROM tm_sys_resource resource,tr_role_resource roleRes,tm_sys_role role " +
            "WHERE roleRes.resource_id = resource.id AND roleRes.role_id = role.id " +
            "AND role.role_code IN ( :roles ) AND resource.res_type IN ( 'api', 'url' ) " +
            ") res where res.res_level<3 " +
            "ORDER BY res.res_level ASC,res.se_qu ASC", nativeQuery = true)
    List<TmSysResource> findRoleResource(@Param("roles") Set<String> roles);

    /**
     * 获取用户对象的api接口结合
     * @param roles
     * @return
     */
    @Query(value = "select CONCAT((select res_code from tm_sys_resource where id=t.parent_id),':',t.res_code) " +
            "from tm_sys_resource t,tr_role_resource tr,tm_sys_role r " +
            "where t.res_type = 'api' " +
            "and tr.resource_id=t.id " +
            "and tr.role_id=r.id " +
            "and r.role_code in(:roles)", nativeQuery = true)
    List<String> findPermissionList(@Param("roles") Set<String> roles);
}
